﻿using AutoMapper;
using BW.MesProject.Public.Domain.RBAC;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using BW.MesProject.WareHouse.Domain;
using BW.MesProject.WareHouse.Infrastructure;
using BW.MesProject.WareHouse.Infrastructure.Dto.Input;
using BW.MesProject.WareHouse.Infrastructure.Dto.OutPut;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.WareHouse.Application
{
    /// <summary>
    /// 工艺管理顺序
    /// </summary>
    public class ProcessServices : IProcessServices
    {
        private readonly IBaseRepository<ProcessFileModel> _ProcessFile;
        private readonly IBaseRepository<ProcessItemModel> _ProcessItem;
        private readonly IBaseRepository<ProcessModel> _Process;
        private readonly IBaseRepository<EMPModel> _EMP;
        private readonly IBaseRepository<DEPModel> _DEP;
        private readonly IBaseRepository<TypeCodeModel> _Code;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ProcessFile"></param>
        /// <param name="ProcessItem"></param>
        /// <param name="Process"></param>
        /// <param name="mapper"></param>
        /// <param name="EMP"></param>
        /// <param name="DEP"></param>
        public ProcessServices(IBaseRepository<ProcessFileModel> ProcessFile,
                               IBaseRepository<ProcessItemModel> ProcessItem,
                               IBaseRepository<ProcessModel> Process,
                               IBaseRepository<EMPModel> EMP,
                               IBaseRepository<DEPModel> DEP,
                               IBaseRepository<TypeCodeModel> Code,
                               IMapper mapper)
        {
            _ProcessFile = ProcessFile;
            _ProcessItem = ProcessItem;
            _Process = Process;
            _EMP = EMP;
            _DEP = DEP;
            _Code = Code;
            this._mapper = mapper;
        }

        #region 工艺管理

        /// <summary>
        /// 查询工艺管理列表
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns>工艺管理列表</returns>
        public ApiResult<List<ProcessOut>> GetProcessList(QryInput input)
        {
            try
            {
                // 构建查询条件
                var query = _Process.GetAll();

                // 根据编号过滤
                if (!string.IsNullOrEmpty(input.QryID))
                {
                    query = query.Where(p => p.PRId.Contains(input.QryID));
                }

                // 根据名称过滤
                if (!string.IsNullOrEmpty(input.QryName))
                {
                    query = query.Where(p => p.PRName.Contains(input.QryName));
                }

                // 获取总记录数
                var totalCount = query.Count();


                var query1 = query.LeftJoin<UserModel>((a, b) => a.EmpId == b.UserId).LeftJoin<DEPModel>((a, b, c) => a.DepId == c.DepId).Select((a, b, c) =>
                   new ProcessOut
                   {
                       PRId = a.PRId,
                       PRName = a.PRName,
                       PRNum = a.PRNum,
                       JobId = b.JobCode,
                       Memo = a.Memo,//描述
                       EmpId = a.EmpId,
                       EMPName = b.UserName,
                       DepId = a.DepId,
                       DepName = c.DepName,
                   });
                //获取集合
                var queryList = query1?.ToList();
                totalCount = queryList.Count();
                // 分页处理
                if (input.PageSize > 0)
                {
                    queryList = query1
                        .OrderBy(a => a.PRId)
                        .Skip((input.PageNum - 1) * input.PageSize)
                        .Take(input.PageSize)
                        .ToList();
                }

                return new ApiResult<List<ProcessOut>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = queryList,
                    TotalCount = totalCount,
                    PageNum = input.PageNum,
                    PageSize = input.PageSize
                };

            }
            catch (Exception ex)
            {
                return new ApiResult<List<ProcessOut>>
                {
                    Code = ApiEnums.Error,
                    Message = $"查询工艺管理列表失败：{ex.Message}",
                    Data = null,
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 查询工艺管理文件列表
        /// </summary>
        /// <param name="PRId">查询参数</param>
        /// <returns>查询工艺管理文件列表</returns>
        public ApiResult<List<ProcessFileOut>> GetProcessFileList(string PRId)
        {
            try
            {
                // 构建查询条件
                var query = _ProcessFile.GetAll();

                // 根据编号过滤
                if (!string.IsNullOrEmpty(PRId))
                {
                    query = query.Where(p => p.PRId.Contains(PRId));
                }


                // 获取总记录数
                var totalCount = query.Count();


                // 转换为输出模型
                var resultList = new List<ProcessFileOut>();
                var query1 = query.Select(a =>
                  new ProcessFileOut
                  {
                      PRId = a.PRId,
                      PRFId = a.PRFId,
                      PRFName = a.PRFName,
                      Address = a.Address,
                      DownNum = a.DownNum,
                      CreateTime = a.CreateTime
                  });

                return new ApiResult<List<ProcessFileOut>>
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = query1.ToList(),
                    TotalCount = totalCount
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<ProcessFileOut>>
                {
                    Code = ApiEnums.Error,
                    Message = $"查询工艺管理列表文件失败：{ex.Message}",
                    Data = null,
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 查询工艺管理明细列表
        /// </summary>
        /// <param name="PRId">查询参数</param>
        /// <returns>工艺管理明细列表</returns>
        public ApiResult<List<ProcessItemOut>> GetProcessItemList(string PRId)
        {
            try
            {
                // 构建查询条件
                var query = _ProcessItem.GetAll();

                // 根据编号过滤
                if (!string.IsNullOrEmpty(PRId))
                {
                    query = query.Where(p => p.PRId.Contains(PRId));
                }


                // 获取总记录数
                var totalCount = query.Count();
                var query1 = query.LeftJoin<ProcessManagModel>((a, b) => a.PMId == b.PMId).LeftJoin<UserModel>((a, b, c) => b.EmpId == c.UserId).LeftJoin<DEPModel>((a, b, c, d) => b.DepId == d.DepId).Select((a, b, c, d) =>
                  new ProcessItemOut
                  {
                      PId = a.PId,
                      PMId = a.PMId,
                      PMName = b.PMName,
                      PNum = a.PNum,
                      PRId = a.PRId,
                      Memo = a.Memo,//描述
                      EmpId = b.EmpId,
                      EMPName = c.UserName,
                      DepId = b.DepId,
                      DepName = d.DepName,
                  });
                //获取集合
                var queryList = query1?.ToList();

                queryList = query1
                        .OrderBy(a => a.PNum)
                        .ToList();
                //// 分页处理
                //if (input.PageSize > 0)
                //{
                //    queryList = query1
                //        .OrderBy(a => a.PRId)
                //        .Skip((input.PageNum - 1) * input.PageSize)
                //        .Take(input.PageSize)
                //        .ToList();
                //}

                return new ApiResult<List<ProcessItemOut>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = queryList,
                    TotalCount = queryList.Count(),
                    PageNum = 0,
                    PageSize = 0
                };

                //// 转换为输出模型
                //var resultList = new List<ProcessItemOut>();

                //foreach (var item in query.ToList())
                //{
                //    var processitemOut = _mapper.Map<ProcessItemOut>(item);

                //    resultList.Add(processitemOut);
                //}

                //return new ApiResult<List<ProcessItemOut>>
                //{
                //    Code = ApiEnums.Success,
                //    Message = "查询成功",
                //    Data = resultList,
                //    TotalCount = totalCount
                //};
            }
            catch (Exception ex)
            {
                return new ApiResult<List<ProcessItemOut>>
                {
                    Code = ApiEnums.Error,
                    Message = $"查询工艺管理列表明细失败：{ex.Message}",
                    Data = null,
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 获取工艺管理详情
        /// </summary>
        /// <param name="processId">工艺管理ID</param>
        /// <returns>工艺管理详情</returns>
        public ApiResult<ProcessOut> GetProcessDetail(string processId)
        {
            try
            {
                if (string.IsNullOrEmpty(processId))
                {
                    return new ApiResult<ProcessOut>
                    {
                        Code = ApiEnums.Fail,
                        Message = "工艺管理ID不能为空",
                        Data = null
                    };
                }

                // 查询工艺管理基本信息
                var process = _Process.GetValue(p => p.PRId == processId);
                if (process == null)
                {
                    return new ApiResult<ProcessOut>
                    {
                        Code = ApiEnums.Fail,
                        Message = "未找到指定的工艺管理信息",
                        Data = null
                    };
                }

                // 转换为输出模型
                var result = _mapper.Map<ProcessOut>(process);

                // 查询关联的员工信息
                if (!string.IsNullOrEmpty(process.EmpId))
                {
                    var emp = _EMP.GetValue(e => e.EMPID == process.EmpId);
                    if (emp != null)
                    {
                        result.EMPName = emp.EMPName;
                    }
                }

                // 查询关联的部门信息
                if (!string.IsNullOrEmpty(process.DepId))
                {
                    var dep = _DEP.GetValue(d => d.DepId == process.DepId);
                    if (dep != null)
                    {
                        result.DepName = dep.DepName;
                    }
                }

                return new ApiResult<ProcessOut>
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProcessOut>
                {
                    Code = ApiEnums.Error,
                    Message = $"查询工艺管理详情失败：{ex.Message}",
                    Data = null
                };
            }
        }
        /// <summary>
        /// 修改工艺管理信息
        /// </summary>
        /// <param name="Process">工艺管理基本信息</param>
        /// <param name="ProcessFile">工艺管理文件信息列表</param>
        /// <param name="ProcessItem">工艺管理顺序信息列表</param>
        /// <returns>修改结果</returns>
        public async Task<ApiResult<bool>> UpdateProcess(ProcessModel Process, List<ProcessFileModel> ProcessFile, List<ProcessItemModel> ProcessItem)
        {
            // 参数校验
            if (Process == null || string.IsNullOrEmpty(Process.PRId))
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Message = "工艺管理信息不完整，PRId不能为空",
                    Data = false
                };
            }

            // 获取数据库上下文，用于事务处理
            var db = _Process.GetAll().Context;
            try
            {
                // 开始事务
                db.Ado.BeginTran();

                // 1. 更新工艺管理基本信息
                var processEntity = _Process.GetValue(x => x.PRId == Process.PRId);
                if (processEntity == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = $"未找到ID为 {Process.PRId} 的工艺管理基本信息",
                        Data = false
                    };
                }

                // 更新字段（使用直接更新而不是先映射再更新，减少一次对象创建）
                var updateProcessResult = _Process.Update(Process);
                if (updateProcessResult <= 0)
                {
                    throw new Exception("更新工艺管理基本信息失败");
                }

                // 2. 处理工艺管理文件信息
                if (ProcessFile != null && ProcessFile.Any())
                {
                    // 先删除旧记录
                    var oldFiles = _ProcessFile.GetAll().Where(x => x.PRId == Process.PRId).ToList();
                    foreach (var oldFile in oldFiles)
                    {
                        var deleteResult = _ProcessFile.Delete(oldFile);
                        if (deleteResult <= 0)
                        {
                            throw new Exception($"删除原工艺文件记录失败，文件ID: {oldFile.PRFId}");
                        }
                    }

                    // 添加新记录
                    foreach (var file in ProcessFile)
                    {
                        file.PRId = Process.PRId; // 确保关联正确
                        // 如果没有文件ID，则生成一个
                        if (string.IsNullOrEmpty(file.PRFId) || file.PRFId == "0")
                        {
                            //file.PRFId = YitIdHelper.NextId().ToString();
                            file.PRFId = await GetCode(CodeType.ProcessFile);// YitIdHelper.NextId().ToString();
                        }

                        var addFileResult = _ProcessFile.Add(file);
                        if (addFileResult <= 0)
                        {
                            throw new Exception($"添加工艺管理文件记录失败");
                        }
                    }
                }

                // 3. 处理工艺管理顺序信息
                if (ProcessItem != null && ProcessItem.Any())
                {
                    // 先删除旧记录
                    var oldItems = _ProcessItem.GetAll().Where(x => x.PRId == Process.PRId).ToList();
                    foreach (var oldItem in oldItems)
                    {
                        var deleteResult = _ProcessItem.Delete(oldItem);
                        if (deleteResult <= 0)
                        {
                            throw new Exception($"删除原工艺顺序记录失败，顺序ID: {oldItem.PId}");
                        }
                    }

                    // 添加新记录
                    foreach (var item in ProcessItem)
                    {
                        item.PRId = Process.PRId; // 确保关联正确
                        // 如果没有顺序ID，则生成一个
                        if (string.IsNullOrEmpty(item.PId) || item.PId == "0")
                        {
                            //item.PId = YitIdHelper.NextId().ToString();
                            item.PId = await GetCode(CodeType.ProcessItem);// YitIdHelper.NextId().ToString();
                        }
                        //item.CreateTime = DateTime.Now;

                        var addItemResult = _ProcessItem.Add(item);
                        if (addItemResult <= 0)
                        {
                            throw new Exception($"添加工艺管理顺序记录失败");
                        }
                    }
                }

                // 提交事务
                db.Ado.CommitTran();

                return new ApiResult<bool>
                {
                    Code = ApiEnums.Success,
                    Message = "更新工艺管理信息成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                // 回滚事务
                db.Ado.RollbackTran();

                return new ApiResult<bool>
                {
                    Code = ApiEnums.Error,
                    Message = $"更新工艺管理信息失败：{ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 删除工艺管理信息
        /// </summary>
        /// <param name="processId">工艺管理ID</param>
        /// <returns>删除结果</returns>
        public ApiResult<bool> DeleteProcess(string processId)
        {
            // 获取数据库上下文，用于事务处理
            var db = _Process.GetAll().Context;
            try
            {
                // 开始事务
                db.Ado.BeginTran();

                // 查询工艺管理基本信息
                var processEntity = _Process.GetValue(x => x.PRId == processId);
                if (processEntity == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = "未找到对应的工艺管理信息",
                        Data = false
                    };
                }

                // 1. 删除工艺管理文件信息
                var processFiles = _ProcessFile.GetAll().Where(x => x.PRId == processId).ToList();
                foreach (var file in processFiles)
                {
                    var deleteFileResult = _ProcessFile.Delete(file);
                    if (deleteFileResult <= 0)
                    {
                        throw new Exception("删除工艺管理文件信息失败");
                    }
                }

                // 2. 删除工艺管理顺序信息
                var processItems = _ProcessItem.GetAll().Where(x => x.PRId == processId).ToList();
                foreach (var item in processItems)
                {
                    var deleteItemResult = _ProcessItem.Delete(item);
                    if (deleteItemResult <= 0)
                    {
                        throw new Exception("删除工艺管理顺序信息失败");
                    }
                }

                // 3. 删除工艺管理基本信息
                var deleteProcessResult = _Process.Delete(processEntity);
                if (deleteProcessResult <= 0)
                {
                    throw new Exception("删除工艺管理基本信息失败");
                }

                // 提交事务
                db.Ado.CommitTran();

                return new ApiResult<bool>
                {
                    Code = ApiEnums.Success,
                    Message = "删除工艺管理信息成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                // 回滚事务
                db.Ado.RollbackTran();

                return new ApiResult<bool>
                {
                    Code = ApiEnums.Error,
                    Message = $"删除工艺管理信息失败：{ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 添加工艺管理信息
        /// </summary>
        /// <param name="Process">工艺管理基本信息</param>
        /// <param name="ProcessFile">工艺管理文件信息列表</param>
        /// <param name="ProcessItem">工艺管理顺序信息列表</param>
        /// <returns>添加结果</returns>
        public ApiResult<int> AddProcess(ProcessModel Process, List<ProcessFileModel> ProcessFile, List<ProcessItemModel> ProcessItem)
        {
            // 参数校验
            if (Process == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Message = "工艺管理基本信息不能为空",
                    Data = 0
                };
            }

            if (string.IsNullOrEmpty(Process.PRName))
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Message = "工艺管理名称不能为空",
                    Data = 0
                };
            }

            // 获取数据库上下文，用于事务处理
            var db = _Process.GetAll().Context;
            try
            {
                // 开始事务
                db.Ado.BeginTran();

                // 生成工艺管理ID（如果未提供）
                if (string.IsNullOrEmpty(Process.PRId))
                {
                    Process.PRId = YitIdHelper.NextId().ToString();
                }
                else
                {
                    // 检查ID是否已存在
                    var existingProcess = _Process.GetValue(x => x.PRId == Process.PRId);
                    if (existingProcess != null)
                    {
                        return new ApiResult<int>
                        {
                            Code = ApiEnums.Fail,
                            Message = $"工艺管理编码 {Process.PRId} 已存在",
                            Data = 0
                        };
                    }
                }

                // 添加工艺管理基本信息
                var processResult = _Process.Add(Process);
                if (processResult <= 0)
                {
                    throw new Exception("添加工艺管理基本信息失败");
                }

                // 添加工艺管理文件信息列表
                if (ProcessFile != null && ProcessFile.Any())
                {
                    foreach (var file in ProcessFile)
                    {
                        // 生成文件ID（如果未提供）
                        if (string.IsNullOrEmpty(file.PRFId))
                        {
                            file.PRFId = YitIdHelper.NextId().ToString();
                        }

                        file.PRId = Process.PRId; // 关联工艺编码

                        var processFileResult = _ProcessFile.Add(file);
                        if (processFileResult <= 0)
                        {
                            throw new Exception("添加工艺管理文件失败");
                        }
                    }
                }

                // 添加工艺管理顺序信息列表
                if (ProcessItem != null && ProcessItem.Any())
                {
                    foreach (var item in ProcessItem)
                    {
                        // 生成顺序ID（如果未提供）
                        if (string.IsNullOrEmpty(item.PId))
                        {
                            item.PId = YitIdHelper.NextId().ToString();
                        }

                        item.PRId = Process.PRId; // 关联工艺编码

                        var processItemResult = _ProcessItem.Add(item);
                        if (processItemResult <= 0)
                        {
                            throw new Exception("添加工艺管理顺序失败");
                        }
                    }
                }

                // 提交事务
                db.Ado.CommitTran();

                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Data = processResult,
                    Message = "工艺管理添加成功"
                };
            }
            catch (Exception ex)
            {
                // 回滚事务
                db.Ado.RollbackTran();

                return new ApiResult<int>
                {
                    Code = ApiEnums.Error,
                    Message = $"添加工艺管理失败：{ex.Message}",
                    Data = 0
                };
            }
        }
        /// <summary>
        /// 添加工艺管理信息
        /// </summary>
        /// <param name="Process">工艺管理基本信息</param>
        /// <param name="ProcessFile">工艺管理文件信息列表</param>
        /// <param name="ProcessItem">工艺管理顺序信息列表</param>
        /// <returns>添加结果</returns>
        public async Task<ApiResult<int>> AddProcessNew(ProcessModel Process, List<ProcessFileModel> ProcessFile, List<ProcessItemModel> ProcessItem)
        {
            // 参数校验
            if (Process == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Message = "工艺管理基本信息不能为空",
                    Data = 0
                };
            }

            if (string.IsNullOrEmpty(Process.PRName))
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Message = "工艺管理名称不能为空",
                    Data = 0
                };
            }

            // 获取数据库上下文，用于事务处理
            var db = _Process.GetAll().Context;
            try
            {
                // 开始事务
                db.Ado.BeginTran();

                // 生成工艺管理ID（如果未提供）
                if (string.IsNullOrEmpty(Process.PRId))
                {
                    Process.PRId = YitIdHelper.NextId().ToString();
                }
                else
                {
                    // 检查ID是否已存在
                    var existingProcess = _Process.GetValue(x => x.PRId == Process.PRId);
                    if (existingProcess != null)
                    {
                        return new ApiResult<int>
                        {
                            Code = ApiEnums.Fail,
                            Message = $"工艺管理编码 {Process.PRId} 已存在",
                            Data = 0
                        };
                    }
                }

                // 添加工艺管理基本信息
                var processResult = _Process.Add(Process);
                if (processResult <= 0)
                {
                    throw new Exception("添加工艺管理基本信息失败");
                }

                // 添加工艺管理文件信息列表
                if (ProcessFile != null && ProcessFile.Any())
                {
                    foreach (var file in ProcessFile)
                    {
                        // 生成文件ID（如果未提供）
                        if (string.IsNullOrEmpty(file.PRFId) || file.PRFId == "0")
                        {
                            file.PRFId = await GetCode(CodeType.ProcessFile);// YitIdHelper.NextId().ToString();
                        }

                        file.PRId = Process.PRId; // 关联工艺编码

                        var processFileResult = _ProcessFile.Add(file);
                        if (processFileResult <= 0)
                        {
                            throw new Exception("添加工艺管理文件失败");
                        }
                        else
                        {
                            TypeCodeModel model = new TypeCodeModel();
                            model.Code = file.PRFId;
                            model.CodeType = GetPrefix(CodeType.ProcessFile);
                            model.CodeTypeName = "工艺文件";
                            ApiResult<int> PF = UpdateCode(model);
                            if (PF.Code != ApiEnums.Success)
                            {
                                throw new Exception("添加工艺管理文件失败");
                            }
                        }
                    }
                }

                // 添加工艺管理顺序信息列表
                if (ProcessItem != null && ProcessItem.Any())
                {
                    foreach (var item in ProcessItem)
                    {
                        // 生成文件ID（如果未提供）
                        if (string.IsNullOrEmpty(item.PId) || item.PId == "0")
                        {
                            item.PId = await GetCode(CodeType.ProcessItem);// YitIdHelper.NextId().ToString();
                        }

                        item.PRId = Process.PRId; // 关联工艺编码

                        var processItemResult = _ProcessItem.Add(item);
                        if (processItemResult <= 0)
                        {
                            throw new Exception("添加工艺顺序失败");
                        }
                        else
                        {
                            TypeCodeModel model = new TypeCodeModel();
                            model.Code = item.PId;
                            model.CodeType = GetPrefix(CodeType.ProcessItem);
                            model.CodeTypeName = "工艺顺序";
                            ApiResult<int> PF = UpdateCode(model);
                            if (PF.Code != ApiEnums.Success)
                            {
                                throw new Exception("添加工艺顺序失败");
                            }
                        }


                    }
                }

                // 提交事务
                db.Ado.CommitTran();

                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Data = processResult,
                    Message = "工艺管理添加成功"
                };
            }
            catch (Exception ex)
            {
                // 回滚事务
                db.Ado.RollbackTran();

                return new ApiResult<int>
                {
                    Code = ApiEnums.Error,
                    Message = $"添加工艺管理失败：{ex.Message}",
                    Data = 0
                };
            }
        }
        #endregion


        /// <summary>
        /// 查询编码
        /// </summary>
        /// <param name="Type"></param>
        /// <returns></returns>
        public ApiResult<TypeCodeModel> GetCode(string Type)
        {
            try
            {
                int totalCount = 0;
                //查询名称来显示数据
                var list = _Code.GetValue(x => x.CodeType == Type);
                return new ApiResult<TypeCodeModel>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = list,
                    TotalCount = totalCount,
                    PageNum = 0,
                    PageSize = 0
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询编码信息时发生异常: {ex.Message}");
                return new ApiResult<TypeCodeModel>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"查询失败: {ex.Message}",
                    Data = new TypeCodeModel(),
                    TotalCount = 0,
                    PageNum = 0,
                    PageSize = 0
                };
            }

        }

        /// <summary>
        /// 修改编码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateCode(TypeCodeModel model)
        {
            var Data = _Code.Update(model);
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "修改成功",
                Data = Data,
                TotalCount = 0
            };
        }


        /// <summary>
        /// 获取标签编码
        /// </summary>
        private async Task<string> GetCode(CodeType codeType)
        {
            string codePrefix = GetPrefix(codeType);
            // 首先尝试直接生成一个新编码作为备选
            string fallbackCode = GenerateCode(codeType);
            try
            {

                ApiResult<TypeCodeModel> typeModel = GetCode(codePrefix);

                if (typeModel == null || typeModel.Data == null)
                {
                    return fallbackCode;
                }

                string lastCode = typeModel.Data.Code;

                if (string.IsNullOrEmpty(lastCode))
                {
                    return fallbackCode;
                }

                // 获取数字部分（后五位或全部，如果不足五位）
                string numberPart;
                string prefixPart;

                // 提取数字部分和前缀部分
                if (lastCode.Length >= 5)
                {
                    // 如果编码长度超过5位，提取最后5位作为数字部分，其余作为前缀
                    numberPart = lastCode.Substring(lastCode.Length - 5);
                    prefixPart = lastCode.Substring(0, lastCode.Length - 5);
                }
                else
                {
                    // 如果编码长度不足5位，就用整个编码作为数字部分，前缀为空
                    numberPart = lastCode;
                    prefixPart = "";
                }

                // 尝试解析为数字并自增1
                if (int.TryParse(numberPart, out int lastNumber))
                {
                    // 使用互联网时间获取当前日期字符串
                    string currentDateStr = DateTime.Now.ToString("yyMMdd");
                    string dateInPrefix = "";

                    // 检查前缀中是否包含日期信息
                    if (prefixPart.Length >= 8 && prefixPart.StartsWith(codePrefix))
                    {
                        dateInPrefix = prefixPart.Substring(2, 6);
                    }

                    // 如果前缀中的日期与当前日期不同，或者前缀不合规范，则重置编号并使用新日期
                    if (string.IsNullOrEmpty(prefixPart) || !prefixPart.StartsWith(codePrefix) ||
                        (dateInPrefix != currentDateStr && !string.IsNullOrEmpty(dateInPrefix)))
                    {
                        // 新的一天，编号从1开始
                        prefixPart = codePrefix + currentDateStr;
                        lastNumber = 1; // 重置为1
                    }
                    else
                    {
                        // 同一天，编号递增
                        lastNumber++;
                    }

                    // 数字部分解析成功，确保是5位数（前面补0）
                    string fiveDigitNumber = lastNumber.ToString("D5");

                    // 组合新编码
                    string newCode = prefixPart + fiveDigitNumber;
                    return newCode;
                }
                else
                {
                    return fallbackCode;
                }
            }
            catch (Exception ex)
            {
                //System.Diagnostics.Debug.WriteLine($"获取编码异常: {ex.Message}");
                return fallbackCode;
            }
        }


        /// <summary>
        /// 查询表是否有该编码
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public ApiResult<int> GetCode(string Id, string name)
        {
            if (name == "Process")
            {
                var model = _Process.GetValue(x => x.PRId == Id);
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "成功",
                    Data = 1,
                    TotalCount = 0
                };
            }
            else if (name == "ProcessItem")
            {
                var model = _ProcessItem.GetValue(x => x.PId == Id);
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "成功",
                    Data = 1,
                    TotalCount = 0
                };
            }
            else if (name == "ProcessFile")
            {
                var model = _ProcessFile.GetValue(x => x.PRFId == Id);
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "成功",
                    Data = 1,
                    TotalCount = 0
                };
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Error,
                Message = "失败",
                Data = 1,
                TotalCount = 0
            };
        }


        /// <summary>
        /// 自动生成编码，格式为XX年月日XXXXX
        /// </summary>
        /// <param name="codeType">编码类型</param>
        /// <param name="lastCode">最后一个编码，用于递增，如果为空则从00001开始</param>
        /// <returns>生成的新编码</returns>
        public static string GenerateCode(CodeType codeType, string lastCode = null)
        {
            // 获取当前日期
            string dateStr = DateTime.Now.ToString("yyMMdd");

            // 根据类型获取前缀
            string prefix = GetPrefix(codeType);

            // 如果没有提供最后一个编码，或者最后一个编码格式不符合要求，则从00001开始
            int serialNumber = 1;

            // 尝试从最后一个编码中提取序列号
            if (!string.IsNullOrEmpty(lastCode) && lastCode.Length >= 13)
            {
                string lastDateAndSerial = lastCode.Substring(2); // 去掉前缀

                // 如果日期相同，则序列号加1；否则从00001开始
                if (lastDateAndSerial.StartsWith(dateStr))
                {
                    string lastSerialStr = lastDateAndSerial.Substring(6); // 获取序列号部分
                    if (int.TryParse(lastSerialStr, out int lastSerial))
                    {
                        serialNumber = lastSerial + 1;
                    }
                }
            }

            // 生成5位序列号，前导零填充
            string serialStr = serialNumber.ToString("00000");

            // 组合编码
            return $"{prefix}{dateStr}{serialStr}";
        }

        /// <summary>
        /// 获取不同类型的编码前缀
        /// </summary>
        /// <param name="codeType">编码类型</param>
        /// <returns>编码前缀</returns>
        public static string GetPrefix(CodeType codeType)
        {
            switch (codeType)
            {
                case CodeType.WareHouse:
                    return "WH"; // 仓库
                case CodeType.Location:
                    return "LC"; // 库位
                case CodeType.Area:
                    return "AR"; // 库区
                case CodeType.ExternalTag:
                    return "ET"; // 外部标签
                case CodeType.Shelves:
                    return "SH"; // 货架
                case CodeType.Processclass:
                    return "PC"; // 工艺分类
                case CodeType.ProcessManag:
                    return "PM"; // 工序管理
                case CodeType.Process:
                    return "PR"; // 工艺
                case CodeType.ProcessItem:
                    return "P"; // 工艺顺序
                case CodeType.ProcessFile:
                    return "PF"; // 工艺文件
                case CodeType.Job:
                    return "J"; // 职位
                case CodeType.Dep:
                    return "D"; // 部门
                case CodeType.EMP:
                    return "E"; // 人员
                default:
                    return "XX"; // 默认
            }
        }

    }

    /// <summary>
    /// 编码类型枚举
    /// </summary>
    public enum CodeType
    {
        /// <summary>
        /// 仓库编码
        /// </summary>
        WareHouse,

        /// <summary>
        /// 库位编码
        /// </summary>
        Location,

        /// <summary>
        /// 库区编码
        /// </summary>
        Area,

        /// <summary>
        /// 货架编码
        /// </summary>
        Shelves,

        /// <summary>
        /// 工艺分类
        /// </summary>
        Processclass,

        /// <summary>
        /// 工艺
        /// </summary>
        Process,
        /// <summary>
        /// 工艺明细
        /// </summary>
        ProcessItem,
        /// <summary>
        /// 工艺文件
        /// </summary>
        ProcessFile,

        /// <summary>
        /// 部门
        /// </summary>
        Dep,
        /// <summary>
        /// 职位
        /// </summary>
        Job,
        /// <summary>
        /// 人员
        /// </summary>
        EMP,
        /// <summary>
        /// 工序管理
        /// </summary>
        ProcessManag,
        /// <summary>
        /// 外部标签解析编码
        /// </summary>
        ExternalTag
    }
}
